/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * 递归树形结构查询匹配项
 * @param {Array} tree
 * @param {*} value
 * @param {string} key
 * @returns {object}
 */
export function findTreeNode(tree, value, key = 'id') {
  let node = null
  for (let i = 0, size = tree.length; i < size; i++) {
    const item = tree[i]
    item[key] === value ? (node = item) : ''
    if (node) break
    if (item.children && item.children.length) {
      node = findTreeNode(item.children, value, key)
    }
  }
  return node
}

/**
 * 递归树形结构查询匹配项
 * @param {Array} tree
 * @param {*} value
 * @param {string} key
 * @returns {object}
 */
export function findActiveMenuIndex(tree, parentMenuPath) {
  let node = null
  for (let i = 0, size = tree.length; i < size; i++) {
    const item = tree[i]
    if (item.path === parentMenuPath) {
      node = item
      break
    }
    if (item.children && item.children.length) {
      node = findActiveMenuIndex(item.children, parentMenuPath)
      if (node) {
        break
      }
    }
  }
  return node
}

/**
 * 数组转树形数组结构
 * @param {Array} tree
 * @param {*} value
 * @param {string} key
 * @returns {Array}
 */
export function toTree(data, rootId = 0, key = 'id', pk = 'parent_id') {
  const result = []
  if (!Array.isArray(data)) {
    return result
  }
  const map = {}
  for (var i = 0, size = data.length; i < size; i++) {
    var id = data[i][key]
    map[id] = data[i]
  }

  for (const i in map) {
    var item = map[i]
    var pid = item[pk]
    const parent = map[pid]
    if (parent) {
      var children = parent.children || []
      parent.children = [...children, item]
    } else {
      if (rootId === pid) {
        result.push(item)
      }
    }
  }
  return result
}

/**
 * 数组转树形数组结构
 * @param {Array} tree
 * @param {*} value
 * @param {string} key
 * @returns {Array}
 */
export function explainTree(data) {
  var result = []
  if (!Array.isArray(data)) {
    return result
  }
  for (var i = 0; i < data.length; i++) {
    var item = data[i]
    const { children, ...params } = item
    var items = (children && children.length) || 0

    if (items) {
      var childs = explainTree(children)
      result = result.concat(childs)
    }
    result.push({ ...params, items: items })
  }
  return result
}
/**
 * 数组转树形数组结构
 * @param {Array} tree
 * @param {*} value
 * @param {string} key
 * @returns {Array}
 */
export function explainTreeLeaf(data, childkey = 'children') {
  var result = []
  if (!Array.isArray(data)) {
    return result
  }
  for (var i = 0; i < data.length; i++) {
    var item = data[i]
    var children = item[childkey] || []
    if (children.length) {
      var childs = explainTreeLeaf(children, childkey)
      result = result.concat(childs)
    } else {
      var filterItem = { ...item }
      delete filterItem[childkey]
      result.push(filterItem)
    }
  }
  return result
}

export function isFileStream(res) {
  return (
    res &&
    typeof res === 'object' &&
    (Object.prototype.toString.call(res) === '[object Blob]' ||
      Object.prototype.toString.call(res) === '[object ArrayBuffer]')
  )
}

export function matchContentType(headers) {
  if (!headers) {
    return null
  }
  const contentType = headers['content-type'] && headers['content-type'].match(/([^;]+)/)
  if (!contentType) {
    return null
  }
  return {
    type: contentType[0]
  }
}

export function matchContentDispositionFilename(headers) {
  if (!headers) {
    return ''
  }
  const contentDisposition = headers['content-disposition']
  if (!contentDisposition) {
    return ''
  }
  // attachment; filename="2022nian02yue11ri-wu liu gong si dui zhao biao.xlsx";
  // filename*=utf-8''2022%E5%B9%B402%E6%9C%8811%E6%97%A5-%E7%89%A9%E6%B5%81%E5%85%AC%E5%8F%B8%E5%AF%B9%E7%85%A7%E8%A1%A8.xlsx
  var unicodeFilename = contentDisposition.split('filename*=')[1]

  var charset = 'utf-8'
  var filename = ''
  if (unicodeFilename) {
    const names = unicodeFilename.split("'")
    charset = names.shift()
    filename = names.pop()
  } else {
    filename = contentDisposition.split('filename=')[1]
  }
  if (!filename) {
    return ''
  }
  return trimString(window.decodeURI(filename, charset), '"')
}

/**
 * 笛卡尔积算法
 * @param {array} args
 * @returns {array}
 */
export function cartesianProduct(...args) {
  return args.reduce(
    (total, current) => {
      const ret = []
      total.forEach(a => {
        current.forEach(b => {
          ret.push(a.concat([b]))
        })
      })
      return ret
    },
    [[]]
  )
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xdc00 && code <= 0xdfff) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * 产生随机整数，包含下限值，包括上限值
 * @param {Number} lower 下限
 * @param {Number} upper 上限
 * @return {Number} 返回在下限到上限之间的一个随机整数
 */
export function random(lower, upper) {
  return Math.floor(Math.random() * (upper - lower + 1)) + lower
}
/**
 * 产生随机整数，包含下限值，包括上限值
 * @param {Number} lower 下限
 * @param {Number} upper 上限
 * @return {Number} 返回在下限到上限之间的一个随机整数
 */
export function trimString(str, char, type = 0) {
  if (char) {
    if (type === -1) {
      return str.replace(new RegExp('^\\' + char + '+', 'g'), '')
    } else if (type === 1) {
      return str.replace(new RegExp('\\' + char + '+$', 'g'), '')
    } else {
      return str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '')
    }
  } else {
    return str.replace(/^\s+|\s+$/g, '')
  }
}
/**
 * 产生随机整数，包含下限值，包括上限值
 * @param {Number} lower 下限
 * @param {Number} upper 上限
 * @return {Number} 返回在下限到上限之间的一个随机整数
 */
export function ltrim(str, char) {
  return trimString(str, char, -1)
}
/**
 * 产生随机整数，包含下限值，包括上限值
 * @param {Number} lower 下限
 * @param {Number} upper 上限
 * @return {Number} 返回在下限到上限之间的一个随机整数
 */
export function rtrim(str, char) {
  return trimString(str, char, 1)
}

/**
 * 生成随机字符串
 *
 * @param {Number} length 长度
 * @param {Boolean} numeric 是否返回数字
 * @param {Boolean} easy 是否返回数字
 * @return string 字符串
 */
export function randomString(length, numeric = false, easy = true) {
  let text = ''
  var possible = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  if (numeric) {
    possible = '0123456789'
  } else if (easy) {
    var chars = ['O', 'o', 'I', 'L', 'l', '0', '1']
    var dchars = ['O', 'o', 'I', 'L', 'l', '0', '1']
    for (var i = 0; i < chars; i++) {
      possible = possible.replace(chars[i], dchars[i])
    }
  }
  for (let i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length))
  }
  return text
}

/**
 * 生成上传文件的文件名
 *
 * @param	string	$ext    扩展名
 * @return	string	返回文件名
 */
export function generateUploadFileName(ext = '') {
  var tempname = randomString(32)
  if (ext) {
    return tempname + '.' + ltrim(ext, '.')
  }
  return tempname
}

/**
 * 根据源对象合并
 *
 * @param	{Object}	source
 * @param	{Object}	data
 * @return {Object}	返回合并后的对象
 */
export function objectFillMerge(source, data) {
  if (typeof source !== 'object' || typeof data !== 'object') {
    return source
  }
  var temp = {}
  Object.keys(source).forEach(key => {
    if (data[key]) {
      temp[key] = data[key]
    }
  })
  return { ...source, ...temp }
}

export function formatFileSize(bytes, decimals = 2, sizeFormatBase = 1024) {
  if (bytes === 0) {
    return '0 B'
  }
  var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  var i = Math.floor(Math.log(bytes) / Math.log(sizeFormatBase))

  var bsize = (bytes / Math.pow(sizeFormatBase, i)).toPrecision(3)

  return parseFloat(bsize).toFixed(decimals) + ' ' + sizes[i]
}

export function arrayUnique(arr) {
  return Array.from(new Set(arr))
}

export function arrayDiff(arr1, arr2) {
  var a1 = arrayUnique(arr1)
  var a2 = arrayUnique(arr2)
  if (a1.length < a2.length) {
    return a2.filter(v => a1.indexOf(v) !== -1)
  } else {
    return a1.filter(v => a2.indexOf(v) !== -1)
  }
}

export default {
  formatFileSize,
  objectFillMerge,
  generateUploadFileName,
  randomString,
  random,
  removeClass,
  addClass,
  hasClass,
  createUniqueString,
  uniqueArr,
  deepClone,
  debounce,
  getTime,
  toggleClass,
  trimString,
  rtrim,
  ltrim,
  objectMerge,
  html2Text,
  param2Obj,
  param,
  cleanArray,
  byteLength,
  getQueryObject,
  formatTime,
  cartesianProduct,
  matchContentDispositionFilename,
  matchContentType,
  isFileStream,
  explainTreeLeaf,
  explainTree,
  toTree,
  findActiveMenuIndex,
  findTreeNode,
  parseTime,
  arrayDiff
}
